package com.scau402.system1.cipher;

import com.alibaba.fastjson2.JSON;
import com.scau402.common.exception.ServiceException;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class CipherHandlerImpl1 implements CipherHandler {
    @Override
    public void checkIsValid(String configStr) {
        Config config = parse(configStr);
        Set<String> set = new HashSet<>();
        for (int key = 0; key < 10; ++key) {
            String value = config.getNumMap().get(String.valueOf(key));
            if (value == null || value.length() != 1 || !StringUtils.isAlpha(value)) {
                throw new ServiceException("数位" + key + "的替换应为单个字母");
            } else if (!set.add(value.toUpperCase()) || !set.add(value.toLowerCase())) {
                throw new ServiceException("数位" + key + "的替换字母" + value + "已重复(不区分大小写)");
            }
        }
    }

    @Override
    public String convert(String configStr, String input) {
        Config config = parse(configStr);
        StringBuilder result = new StringBuilder();
        for (char c : input.toCharArray()) {
            result.append(
                    config.getNumMap().getOrDefault(String.valueOf(c), "")
            );
        }
        return result.toString();
    }

    private Config parse(String configStr) {
        try {
            return JSON.parseObject(configStr, Config.class);
        } catch (Exception e) {
            throw new ServiceException("暗码配置异常");
        }
    }

    @Data
    private static class Config {
        private Map<String, String> numMap;
    }
}
